import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import DexieCtx from "@/utils/dexiectx";
import { getUid } from '@/utils';
import { decodeByPublicKey } from '@/utils/encrypt';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    activeList: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ACTIVE_LIST: (state, list) => {
    state.activeList = list
  },
}

const actions = {
  async loadActives({ commit }) {
    const dexie = await DexieCtx.db()
    let activeList = await dexie.actives.toArray()
    activeList = activeList.map(item => {
      const v = decode(item.value)
      if (v == null) {
        return null
      }
      v.id = item.id
      return v
    })
    activeList = activeList.filter((item) => item != null)
    activeList = avalibalActives(activeList)
    commit('SET_ACTIVE_LIST', activeList)
  },
  async addActive({ dispatch, state }, value) {
    const dexie = await DexieCtx.db()
    const decodedObj = decode(value)
    const isRepeat = state.activeList.find(item => decodedObj.rd == item.rd) != null
    if (isRepeat) {
      console.error("重复的激活码")
      return
    }
    const isMyActive = decodedObj.userid == getUid()
    if (isMyActive == false) {
      console.error("不是本账号激活码")
      return
    }
    await dexie.actives.add({
      value: value
    })
    await dispatch('loadActives')
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const userInfo = {
        roles: ['admin'],
        introduction: 'I am a super administrator',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        name: 'Super Admin'
      }
      const { name, avatar } = userInfo
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      resolve(userInfo)
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

function decode(value) {
  try {
    const valueDecoded = decodeByPublicKey(value)
    const arr = valueDecoded.split("+")
    const date = new Date(parseInt(arr[3]) * 1000);
    return {
      userid: arr[0],
      account: arr[1],
      rd: arr[2],
      time: date.toLocaleString(),
    }
  } catch (error) {
    return null
  }
}

function avalibalActives(activeList) {
  let okList = []
  const myUid = getUid()
  for (let index = 0; index < activeList.length; index++) {
    const ac = activeList[index];
    if (ac.userid != myUid) {
      continue
    }
    const isRepeat = okList.find(item => item.rd == ac.rd) != null
    if (isRepeat) {
      continue
    }
    okList.push(ac)
  }
  return okList
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

